<template>
  <section class="page-content">
    <el-alert
      title="操作提示"
      type="success"
      description="不同的产品模型拥有不同的产品属性，产品属性是给用户看的，不牵涉价钱且用户购买时不能进项选择，例如, 生产日期、生产地、保质期等等~"
      show-icon>
    </el-alert>
    <div class="toolbar">
      <el-form :inline="true" :model="params">
        <el-form-item label="属性列表">
          <el-input v-model="searchData.name" size="small" placeholder="属性名称"></el-input>
        </el-form-item>
        <el-form-item label="产品模型">
          <el-select v-model="searchData.type_id" size="small" placeholder="属性模型">
            <el-option
              label="全部"
              value="">
            </el-option>
            <el-option
              v-for="item in types"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" icon="search" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" size="small" icon="plus" @click="create">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData.data"
      @sort-change="sort"
      border
      style="width: 100%"
      max-height="100%">
      <el-table-column
        prop="id"
        width="80"
        sortable
        label="ID">
      </el-table-column>
      <el-table-column
        prop="name"
        sortable
        label="名称">
      </el-table-column>
      <el-table-column
        prop="type_id"
        sortable
        label="所属模型">
        <template slot-scope="scope">
          {{scope.row.type.name}}
        </template>
      </el-table-column>
      <el-table-column
        prop="input_type"
        sortable
        label="录入方式">
        <template slot-scope="scope">
          <template v-if="scope.row.input_type === 'INPUT'">手动录入</template>
          <template v-if="scope.row.input_type === 'SELECT'">从列表中选择</template>
          <template v-if="scope.row.input_type === 'TEXTAREA'">多行文本</template>
        </template>
      </el-table-column>
      <el-table-column
        label="可选值">
        <template slot-scope="scope">
          <el-tag size="mini" style="margin-right:2px;" :key="v" v-for="v in scope.row.values" v-if="v !== null">{{v}} </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="index"
        sortable
        label="筛选">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.index"
            disabled>
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="created_at"
        sortable
        width="180"
        label="创建时间">
      </el-table-column>
      <el-table-column
        fixed="right"
        width="180"
        label="操作">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editRow(scope.row)"
            type="default"
            size="mini">
            编辑
          </el-button>
          <el-button
            @click.native.prevent="deleteRow(scope.$index, tableData.data)"
            type="danger"
            size="mini">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block toolbar">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="tableData.current_page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="parseInt(tableData.per_page)"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.total">
      </el-pagination>
    </div>
    <!-- dialog -->
    <el-dialog class="dialog" title="新增属性" :visible.sync="visible">
      <el-form :model="formData" ref="formData" :rules="formRules"  label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="名称"></el-input>
        </el-form-item>
        <el-form-item label="所属模型"  prop="type_id">
          <el-select v-model="formData.type_id" placeholder="所属模型">
            <el-option
              v-for="item in types"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="能否进行检索" prop="index">
          <el-switch v-model="formData.index"></el-switch>
        </el-form-item>
        <el-form-item label="属性录入方式" prop="input_type">
          <el-select v-model="formData.input_type" placeholder="请选择属性录入方式">
            <el-option label="手动录入" value="INPUT"></el-option>
            <el-option label="从列表中选择" value="SELECT"></el-option>
            <el-option label="多行文本" value="TEXTAREA"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="formData.input_type === 'SELECT' && formData.values"
          v-for="(val, index) in formData.values"
          :label="'可选值' + parseInt(index+1)"
          :key="index"
          :prop="'values.' + index"
          :rules="{ required: true, message: '请输入可选址', trigger: 'blur'}">
          <el-input class="optional-value" v-model="formData.values[index]"></el-input>
          <el-button v-if="index !== 0" @click.prevent="removeValue(val)">-</el-button>
          <el-button v-if="index === 0" @click.prevent="addValue(val)" type="success">+</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false" :disabled="editLoading">取 消</el-button>
        <el-button type="primary" :loading="editLoading" @click="handleCreateOrEdit('formData')">确 定</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
  import {generateUrl} from '@/utils/helpers'
  export default {
    data () {
      return {
        loading: false,
        types: [],
        tableData: {
          first_page_url: '',
          from: '',
          to: '',
          last_page: '',
          last_page_url: '',
          next_page_url: '',
          prev_page_url: '',
          path: '',
          per_page: 0,
          total: 0,
          data: []
        },
        searchData: {
          name: '',
          type_id: this.$route.query.type_id ? parseInt(this.$route.query.type_id) : ''
        },
        params: {
          order_by: 'id',
          order_type: 'desc',
          page_size: 20,
          name: '',
          type_id: this.$route.query.type_id ? parseInt(this.$route.query.type_id) : '',
          page: 1
        },
        // dialog
        editLoading: false,
        visible: false,
        tempData: {
          id: null,
          type_id: this.$route.query.type_id ? parseInt(this.$route.query.type_id) : '',
          name: '',
          index: false,
          attr_type: 'ONLY',
          values: null
        },
        formData: {},
        formRules: {
          name: [
            { required: true, message: '请输入名称', trigger: 'blur' },
            { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
          ],
          type_id: [
            { required: true, type: 'number', message: '请选择', trigger: 'blur' }
          ],
          input_type: [
            { required: true, message: '请选择', trigger: 'blur' }
          ]
        }
      }
    },
    mounted () {
      this._restFormData()
      this._getData()
      this._getTypes()
    },
    watch: {
      params: {
        deep: true,
        handler (newValue) {
          this._getData()
        }
      }
    },
    methods: {
      removeValue (item) {
        var index = this.formData.values.indexOf(item)
        if (index !== -1) {
          this.formData.values.splice(index, 1)
        }
      },
      addValue () {
        this.formData.values.push('')
      },
      deleteRow (index, rows) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log(rows)
          this.loading = true
          this.$http.delete('/attrs/' + rows[index].id).then((response) => {
            this.loading = false
            this.$message.success('删除成功')
            this.tableData.total--
            rows.splice(index, 1)
          }).catch((error) => {
            this.loading = false
            console.log(error)
          })
        })
      },
      editRow (item) {
        this.formData = Object.assign({}, item)
        this.formData.values = Object.assign([], item.values ? item.values : [''])
        this.visible = true
      },
      onSubmit () {
        this.params.name = this.searchData.name
        this.params.type_id = this.searchData.type_id
      },
      handleSizeChange (val) {
        this.params.page_size = val
      },
      handleCurrentChange (val) {
        this.params.page = val
      },
      sort (data) {
        let orderType = ''
        if (data.order === 'ascending') {
          orderType = 'asc'
        }
        if (data.order === 'descending') {
          orderType = 'desc'
        }
        this.params.order_type = orderType
        this.params.order_by = data.prop
      },
      create () {
        // 填充用户搜索值，创建时减少用户输入数据
        this.tempData.type_id = this.searchData.type_id
        this.tempData.name = this.searchData.name
        // 重置可选值，避免bug
        this.tempData.values = ['']
        this._restFormData()
        this.visible = true
      },

      handleCreateOrEdit (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$http({
              method: this.formData.id === null ? 'post' : 'put',
              url: this.formData.id === null ? '/attrs' : '/attrs/' + this.formData.id,
              data: this.formData
            }).then((response) => {
              this.$message.success(response.data.message)
              this.editLoading = false
              this.visible = false
              this._getData()
            }).catch((error) => {
              this.editLoading = false
              console.log(error)
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      _getTypes () {
        this.$http.get('/types?page_size=1000').then((response) => {
          this.types = response.data.data
        }).catch((error) => {
          console.log(error)
        })
      },
      _restFormData () {
        this.formData = Object.assign({}, this.tempData)
      },
      _getData () {
        let url = generateUrl('/attrs', this.params)
        this.loading = true
        this.$http.get(url).then((response) => {
          this.loading = false
          this.tableData = response.data
        }).catch((error) => {
          this.loading = false
          console.log(error)
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .dialog {
    .el-input {
      width: 80%;
    }
    .el-select {
      width: 80%;
    }
    .optional-value {
      margin-right: 5px;
    }
  } 
</style>
